package com.ruoyi.common.core.web.domain;

import com.ruoyi.common.core.utils.ServletUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

public class ApiResponse implements Serializable {
    private static final long serialVersionUID = 1L;

    private String success;
    private String message;
    private String code;
    private Object result;
    private Long timestamp;
    private String traceId;

    public ApiResponse() {
        this.timestamp = System.currentTimeMillis();
        this.traceId = getTraceId();
    }

    /**
     * 获取请求中的traceId
     */
    private String getTraceId() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
            String traceId = request.getHeader("traceId");
            if (traceId != null && !traceId.isEmpty()) {
                return traceId;
            }
        }

        return java.util.UUID.randomUUID().toString().replace("-", "");
    }

    public static ApiResponse success(String message, Object result) {
        ApiResponse response = new ApiResponse();
        response.setSuccess("true");
        response.setMessage(message);
        response.setCode("200");
        response.setResult(result);
        return response;
    }

    public static ApiResponse error(String code, String message) {
        ApiResponse response = new ApiResponse();
        response.setSuccess("false");
        response.setMessage(message);
        response.setCode(code);
        response.setResult("");
        return response;
    }

    public String getSuccess() {
        return success;
    }

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }



    @Override
    public String toString() {
        return "ApiResponse{" +
                "success='" + success + '\'' +
                ", message='" + message + '\'' +
                ", code='" + code + '\'' +
                ", result=" + result +
                ", timestamp=" + timestamp +
                ", traceId='" + traceId + '\'' +
                '}';
    }
} 